#!/usr/bin/env python
# -*- coding: latin-1 -*-

import sys
from time import sleep, localtime
from weakref import WeakKeyDictionary

from PodSixNet.Server import Server
from PodSixNet.Channel import Channel
from thread import *
from vista.Menu import *

class ClientChannel(Channel):
	"""
	This is the server representation of a single connected client.
	"""
	def __init__(self, *args, **kwargs):
		self.nickname = "anonymous"
		self.id = -1
		Channel.__init__(self, *args, **kwargs)
	
	def Close(self):
		self._server.DelPlayer(self)
	
	def Network_ataque(self, data):
		for p in self._server.players:
			if p.nickname != self.nickname:
				p.Send({"action": "ataque", "ataque": data['ataque'], "quien": data["quien"]})
				
	def Network_respuesta(self, data):
		for p in self._server.players:
			if p.nickname != self.nickname:
				p.Send({"action": "respuesta", "ataque": data["ataque"], "respuesta": data["respuesta"], "quien": data["quien"]})

	def Network_nickname(self, data):		
		self.nickname = data['nickname']
		if [p.nickname for p in self._server.players].count(self.nickname) > 1:
			self.Send({"action": "refused", "msj": "Por favor elija otro nick"})
		if data["passwd"] != self._server.passwd:
			cad = "yo: "+data["passwd"]+" el: "+self._server.passwd
			self.Send({"action": "refused", "msj": "La contraseña es incorrecta"+cad})

class BatallaServer(Server):
	channelClass = ClientChannel
	
	def __init__(self, passwd, *args, **kwargs):
		self.passwd = passwd
		Server.__init__(self, *args, **kwargs)
		self.players = WeakKeyDictionary()
		self.count = 0
	
	def Connected(self, channel, addr):
		if self.count < 2:
			self.count += 1
			self.AddPlayer(channel)
			if self.count == 2:
				self.SendToAll({"action": "colocar", "msj": "Coloque sus barcos y espere"})
		else:
			channel.Send({"action": "refused", "msj": "Esta partida esta llena"})
	
	def AddPlayer(self, player):
		self.players[player] = True
		player.id = self.count
	
	def DelPlayer(self, player):
		del self.players[player]
		self.count -= 1
		self.SendPlayers()
	
	def SendPlayers(self):
		self.SendToAll({"action": "players", "players": [p.nickname for p in self.players]})
	
	def SendToAll(self, data):
		[p.Send(data) for p in self.players]
	
	def Launch(self):
		while True:
			self.Pump()
			sleep(0.0001)

